/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export default {
    props: {
        // 图片列表
        imgList: [],
        // 组件参数
        compAttrs: {},
    },
    data: {
        imageList: [],
        usedList: [],
        curImgUrl: '',
        //背景图和组件的尺寸
        imgWidth: 300,
        imgHeight: 225,

        //滑块的动态位置
        verifieePosLeft: 0,
        startRealXBias: 0, //触摸开始的实际位置
        verifyThreshold: 0.1, // 偏差阈值, 10%以内通过

        //缺口参数
        borderPadding: 0.2, // 边界20%的范围内不会生成缺口
        verifierWidth: 50,
        verifierHeight: 50,
        verifierXBias: 0,
        verifierYBias: 0,
        swipeCircleRadius: 10, //上右突出的半径

        //验证结果弹窗
        ntfWindowPos: -40,
        ntfText: [],
        ntfColor: '',
        playAnim: 'paused',
        funDisabled: false, //使能页面功能

        //提示文字透明度
        textOpacity: 1,

        //时间戳信息
        startTime: 0,
        endTime: 0
    },
    onInit() {
        this.imageList = this.imgList;
        this.imgWidth = this.compAttrs.width;
        this.imgHeight = this.compAttrs.height;
        this.verifierWidth = this.compAttrs.blockSize;
        this.verifierHeight = this.compAttrs.blockSize; // 方块长宽相等
        this.swipeCircleRadius = this.swipeCircleRadius * this.verifierWidth / 50;
        this.newSwipeCaptcha();
    },
    //点击刷新按钮
    onClickRfsBtn(e) {
        this.newSwipeCaptcha();
    },
    //开始拖动
    onSliderStart(e) {
        //记录开始时间和触摸的真实位置
        this.startTime = this.getCurTime();
        this.startRealXBias = e.touches[0].localX;
    },

    //移动slider
    onSliderMove(e) {
        let curX = e.touches[0].localX;
        // 确保不越界
        if (curX <= this.startRealXBias || curX >= this.imgWidth - this.verifierWidth + this.startRealXBias) return;
        // 改变滑块位置
        this.verifieePosLeft = curX - this.startRealXBias;
        // 改变文字透明度
        this.textOpacity = (1 - 3 * (this.verifieePosLeft / this.imgWidth)) >= 0 ? (1 - 3 * (this.verifieePosLeft / this.imgWidth)) : 0;
    },

    //停止拖动
    onSliderStop(e) {
        //记录结束时间
        this.endTime = this.getCurTime();
        //检查滑块位置
        this.checkCaptcha(this.verifieePosLeft);
    },

    // 创建新的滑动验证
    newSwipeCaptcha() {
        //生成随机缺口
        this.genRandomPos();
        // 选择随机图片
        this.selectRdmImg();
    },

    genRandomPos() {
        // 上下左右边框一定距离内不能生成缺口
        // 缺口不与滑块重叠，且不越界
        let xMin = this.verifierWidth + this.swipeCircleRadius + this.verifierWidth * this.borderPadding;
        let xMax = this.imgWidth - this.verifierWidth - this.imgWidth * this.borderPadding;
        let yMin = this.swipeCircleRadius + this.verifierHeight * this.borderPadding;
        let yMax = this.imgHeight - this.verifierHeight - this.imgHeight * this.borderPadding;
        // x-y范围内的随机整数表示为Math.round(Math.random()*(y-x)+x)
        this.verifierXBias = Math.round(Math.random() * (xMax - xMin) + xMin);
        this.verifierYBias = Math.round(Math.random() * (yMax - yMin) + yMin);
    },

    //从列表中随机选择一张
    selectRdmImg() {
        let imgListLength = this.imageList.length;

        if (imgListLength == 0) {
            //图片全部使用过
            this.imageList = this.usedList;
            this.usedList = [];
            imgListLength = this.imageList.length;
        }
        //随机生成index
        let randomIdx = Math.round(Math.random() * (imgListLength - 1));
        this.curImgUrl = this.imageList[randomIdx];
        this.usedList.push(this.imageList.splice(randomIdx, 1)[0]);
    },

    //检验验证是否成功
    checkCaptcha(movement) {
        let userXBias = movement;
        //显示弹窗
        let isValid = userXBias >= this.verifierXBias - this.verifierXBias * this.verifyThreshold
        && userXBias <= this.verifierXBias + this.verifierXBias * this.verifyThreshold;
        this.showVerifyWindow(isValid);
        // 开启弹窗动画
        this.playAnim = 'running';
        // 禁用滑块和刷新
        this.funDisabled = true;
        // 返回结果给父组件
        this.returnRes(isValid);
        // 暂停页面2秒
        setTimeout(() => {
            //重置页面
            this.playAnim = 'paused'; //动画暂停
            this.ntfWindowPos = -40; //隐藏弹窗
            this.textOpacity = 1; //显示提示文本
            this.verifieePosLeft = 0; //滑块归零
            this.newSwipeCaptcha(); //刷新图片
            this.funDisabled = false; //允许使用页面功能
        }, 2000);
    },

    //弹成功失败窗口
    showVerifyWindow(isVerified) {
        if (isVerified) {
            this.ntfText = this.$t('strings.successNtf') +
            " 用时" + ((this.endTime - this.startTime) / 1000).toFixed(1) + "秒";
            this.ntfColor = "#049304";
        } else {
            this.ntfText = this.$t('strings.failNtf');
            this.ntfColor = "#f74a4a";
        }
    },

    //获取当前时间
    getCurTime() {
        return new Date();
    },
    // 返回验证结果
    returnRes(result) {
        this.$emit("handleResult", {
            result: result
        });
    }
}
